import pdb
import serial
import sys
import time
import datetime

#mode: EMU|COM
mode = 'EMU'

def parseContactId(raw):
    e = {}
    e['objId']      = raw[2:6]
    e['msgType']    = raw[6:7]
    e['msgCode']    = raw[7:10]
    e['group']      = raw[10:12]
    e['zone']       = raw[12:15]
    return e

def storeEvent(event):
    p = serial.Serial(port=5, baudrate=1200, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=5, writeTimeout=5,  xonxoff=0, rtscts=0)
#    print p.write('1011\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x40\x20\x20\x20\x20')
#    print p.write('\x14')
#    print p.write('5000 180011E60202003')
#    print p.write('\x14')
    p.write('18' + e['objId'] + e['msgType'] + e['msgCode'] + e['group'] + e['zone'])
    print p.write('\x14')

#    sys.stdout.write('data: "')
#    d = p.readline()
#    for i in d: sys.stdout.write(str(ord(i)))
#    sys.stdout.write('"\n')
#    sys.stdout.flush()
#    p.write('\x50\x10\x20\x18\x00\x01\x03\x11\x00\x20\x03')

if mode == 'EMU':
    e = parseContactId('180001R11002003')
    storeEvent(e)
if mode == 'COM':
    p = serial.Serial(port=2, baudrate=1200, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=0)

    message = ''
    while True:
        try:
            d = p.readline()
            p.write('\x06')
            if d == '': continue
            for i in d:
                if ord(i) in [20, 32]:
                    msg = parseContactId(message)
                    r = getLastEventId(conn.cursor())
                    storeEvent(msg)
                    print msg
                    message = ''
                else: 
                    message += i
        except: continue

    p.close()

